<template>
  <el-dialog v-model="deleteVisible" :title="title" width="70%" align-center @close="cancel"
    :close-on-click-modal="false" destroy-on-close draggable	>
    <div class="content" v-loading="loadingContent">
      <el-form ref="ruleFormRef" :model="ruleForm.role" :rules="rules" label-position="top">
        <el-form-item label="角色" prop="name">
          <el-input v-model="ruleForm.role.name" placeholder="角色名称" class="input-switch" />
          <el-switch v-model="ruleForm.role.status" inline-prompt active-text="启用" inactive-text="禁用" :active-value='1'
            :inactive-value='0' />
        </el-form-item>
      </el-form>
      <el-tabs type="border-card" class="tab-pane">
        <el-tab-pane label="菜单权限">
          <div class="m-[10px]">
          <el-cascader
            v-model="search_list.menu_name"
            :options="menuOptions"
            :props="menuCascaderProps"
            class="w-full"
            placeholder="请搜索"
            filterable
            @remove-tag="handleMenuRemove" :filter-method="customFilterMethod"/>
          </div>
          <el-cascader-panel v-model="ruleForm.role_owner.menu_ids" :options="menuOptions" :props="menuCascaderProps"
            class="cascaderPanel" ref="dataMenu" />
        </el-tab-pane>
        <el-tab-pane label="按钮授权">
          <div class="m-[10px]">
            <el-cascader
              v-model="search_list.button_name"
              :options="buttonOptions"
              :props="cascaderProps"
              class="w-full"
              placeholder="请搜索"
              @remove-tag="handleButtonRemove" :filter-method="customFilterMethod"/>
          </div>
          <el-cascader-panel v-model="ruleForm.role_owner.button_ids" :options="buttonOptions" :props="cascaderProps"
            class="cascaderPanel" ref="dataButton" />
        </el-tab-pane>
        <el-tab-pane label="数据权限">
            <div class="m-[10px]">
              <el-cascader
                v-model="search_list.data_user_name"
                :options="options"
                :props="cascaderProps"
                class="w-full"
                placeholder="请搜索"
                filterable
                @remove-tag="handleDataRemove" :filter-method="customFilterMethod"/>
            </div>
          <el-cascader-panel v-model="ruleForm.role_owner.data_user_ids" :options="options" :props="cascaderProps"
            class="cascaderPanel" ref="dataUser" @change="handleDataUser"/>
        </el-tab-pane>
        <el-tab-pane label="属性权限">
          <div class="attribute">
            <div>
              <div class="text">商品权限</div>
                <div class="m-[10px]">
                  <el-cascader
                    v-model="search_list.goods_category_name"
                    :props="goodsSearchProps"
                    :options="goodsData"
                    class="w-full"
                    filterable
                    placeholder="请搜索"
                    collapse-tags
                    collapse-tags-tooltip
                    @remove-tag="handleGoodsRemove"
                    :filter-method="customFilterMethod"
                  >
                  </el-cascader>
                </div>
              <el-tree :props="goodsProps" :data="goodsData" show-checkbox ref="dataGoods" node-key="id" />
            </div>
            <div class="ml-[8px] mr-[8px]">
              <div class="text">仓库权限</div>
                <div class="m-[10px]">
                  <el-cascader
                    v-model="search_list.warehouse_name"
                    :props="warehouseSearchProps"
                    :options="warehouseData"
                    class="w-full"
                    filterable
                    placeholder="请搜索"
                    collapse-tags
                    collapse-tags-tooltip
                    @remove-tag="handleWarehouseRemove"
                    :filter-method="customFilterMethod"
                  >
                  </el-cascader>
                </div>
              <el-tree :props="warehouseProps" :data="warehouseData" show-checkbox
                :default-checked-keys="ruleForm.role_owner.warehouse_ids" node-key="id" ref="dataWarehouse" />
            </div>
            <div>
              <div class="text">字段权限</div>
                <div class="m-[10px]">
                  <el-cascader
                    v-model="search_list.field_name"
                    :props="menuSearchProps"
                    :options="fieldData"
                    class="w-full"
                    filterable
                    placeholder="请搜索"
                    collapse-tags
                    collapse-tags-tooltip
                    @remove-tag="handleFieldRemove"
                    :filter-method="customFilterMethod"
                  >
                  </el-cascader>
                </div>
              <el-tree :props="menuProps" :data="fieldData" show-checkbox
                :default-checked-keys="ruleForm.role_owner.field_attr_ids" ref="dataField" node-key="id" />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <template #footer>
      <div>
        <el-button @click="cancel" :loading="loading.save">取消</el-button>
        <el-button type="primary" @click="confirm" :loading="loading.save">
          保存
        </el-button>
        <!-- <el-button type="primary" @click="confirmEnable" :loading="loading.saveEnable">
          保存并启用
        </el-button> -->
      </div>
    </template>
  </el-dialog>
</template>
<script setup name="VRole">
import { organizationList } from "@/api/system/role"
import { getMenus } from "@/api/menu"
import { baseData } from '@/api/system/base'
import {updateDepartmentIds,transformIds,simplifyIds,filterTreeByIds,expandSelectedIds} from './data'
import { reactive } from "vue"
const emits = defineEmits(['cancel', 'confirm'])
const dataField = ref()
const dataWarehouse = ref()
const dataGoods = ref()
const dataButton = ref()
const dataMenu = ref()
const dataUser = ref()
const goodsProps = {
  label: 'name',
  children: 'son',
}
const goodsSearchProps = {
    multiple: true,
    emitPath: false,
    value: "id",
    label: "name",
    children: "son",
}
const menuCascaderProps = {
  multiple: true,
  emitPath: false,
  label: 'name',
  value: 'id',
  children: 'sub'
}
const warehouseProps = {
  label: 'label',
  children: 'warehouse',
}
const warehouseSearchProps = {
    multiple: true,
    emitPath: false,
    value: "id",
    label: "label",
    children: "warehouse",
}
const menuProps = {
  label: 'name',
  children: 'sub',
}
const menuSearchProps = {
    multiple: true,
    emitPath: false,
    value: "id",
    label: "name",
    children: "sub",
}
// 声明接收参数
const props = defineProps({
  title: {
    type: String,
    default: "新增"
  },
  formData: {
    type: Object,
    default: {
      role: {
        name: '',
        status: ""
      },
      role_owner: {
        menu_ids: [],
        field_attr_ids: [],
        button_ids: [],
        data_user_ids: [],
        data_dept_ids:[]
      }
    }
  }
})
const data = reactive({
  deleteVisible: false,
  ruleForm: {
    role: {
      name: '',
      status:1
    },
    role_owner: {
      menu_ids: [],
      field_attr_ids: [],
      button_ids: [],
      data_user_ids: [],
      data_dept_ids:[]
    }
  },
  loading: {},
  cascaderProps: {
    emitPath: false,
    multiple: true,
    label: 'name',
    value: 'id',
    children: 'sub'
  },
  options: [],
  menuOptions: [],
  buttonOptions: [],
  goodsData: [],
  warehouseData: [],
  fieldData: [],
  oneGoods: []
})

const ruleFormRef = ref()
const { deleteVisible, ruleForm, loading, cascaderProps, options, buttonOptions, menuOptions, goodsData, warehouseData, fieldData, oneGoods } = toRefs(data)
const { formData } = toRefs(props)
const rules = reactive({
  name: [
    { required: true, message: '角色名称不能为空', trigger: 'blur' },
  ],
})
// watch(() => formData.value, (newVal, oldVal) => {
//   ruleForm.value = JSON.parse(JSON.stringify(newVal))
//   ruleForm.value.role_owner.warehouse_ids.map((res, index) => {
//     ruleForm.value.role_owner.warehouse_ids[index] = '1-' + res
//   })
// })
//递归调用
const treeToArray = tree => {
  const expanded = datas => {
    if (datas && datas.length > 0) {
      datas.forEach(e => {
        if (e.warehouse_id) {
          e.id = '1-' + e.warehouse_id
        }
        e.label = e.attribute_name ? e.attribute_name : e.warehouse_name
        expanded(e.warehouse)
      })
    }
  }
  expanded(tree)
}
//树型数据转为一维数组
const oneArray = tree => {
  const arr = []
  const expanded = datas => {
    if (datas && datas.length > 0) {
      datas.forEach(e => {
        if (e.son) {
          arr.push(e)
        }
        expanded(e.son)
      })
    }
  }
  expanded(tree)
  return arr
}
function convertIdToDid(nodes) {
  return nodes.map(node => {
    // 如果节点的organization_type等于2，则修改id
    if (node.organization_type === 1) {
      node.id = `d${node.id}`;
    }
    // 如果存在子节点数组sub，则递归处理
    if (node.sub && Array.isArray(node.sub)) {
      node.sub = convertIdToDid(node.sub);
    }
    return node;
  });
}
function convertIdToField(nodes) {
  return nodes.map(node => {
    // 如果节点的organization_type等于2，则修改id
    if (node.field_type === 1) {
      node.id = `f${node.id}`;
    }
    // 如果存在子节点数组sub，则递归处理
    if (node.sub && Array.isArray(node.sub)) {
      node.sub = convertIdToField(node.sub);
    }
    return node;
  });
}
const loadingContent = ref(false)
const cateUserIds = ref([])
const open = async (val) => {
  deleteVisible.value = true
  loadingContent.value = true
  if(Object.keys(val).length !== 0){
    ruleForm.value = JSON.parse(JSON.stringify(val))
    ruleForm.value.role_owner.warehouse_ids.map((res, index) => {
      ruleForm.value.role_owner.warehouse_ids[index] = '1-' + res
    })
  }
  await baseData({ get: ['access'] }).then(res => {
    menuOptions.value = res.data.access
      .menu_options
    buttonOptions.value = res.data.access
      .button_options
    goodsData.value = res.data.access
      .goods_category_options
    warehouseData.value = res.data.access
      .warehouse_options
    treeToArray(warehouseData.value)
    // fieldData.value = res.data.access
    //   .field_attr_options
    fieldData.value = convertIdToField(res.data.access.field_attr_options)
    oneGoods.value = oneArray(res.data.access
      .goods_category_options)
    let arr = []
    arr = ruleForm.value?.role_owner.goods_category_ids?.filter(e => oneGoods.value?.some(a => a.son.length && a.id === e))
    ruleForm.value.role_owner.goods_category_ids = ruleForm.value?.role_owner.goods_category_ids?.filter(e => !arr.includes(e))
    dataGoods.value.setCheckedKeys(ruleForm.value.role_owner.goods_category_ids || [], true)
  }).finally(()=>{
    loadingContent.value = false
  })
  loadingContent.value = true
  await organizationList().then(res => {
    // let orgDeptData = convertIdToDid(res.data)
    const { updatedTree, duplicateUserIds } = updateDepartmentIds(res.data);
    options.value = updatedTree
    cateUserIds.value = duplicateUserIds
    console.log(cateUserIds.value);
  }).finally(()=>{
    loadingContent.value = false
  })
  if(Object.keys(val).length !== 0){
    let personnel = transformIds(cateUserIds.value, ruleForm.value.role_owner.data_user_ids || []);
    ruleForm.value.role_owner.data_user_ids = personnel
  }
}

const lastCheckedIds = ref([]);

const handleDataUser = (val) => {
  const updated = expandSelectedIds(cateUserIds.value, val || [], lastCheckedIds.value);
  ruleForm.value.role_owner.data_user_ids = updated;
  lastCheckedIds.value = updated;
};

const confirm = () => {
  let { validate } = ruleFormRef.value
  validate((valid) => {
    if (valid) {
      // const obj = JSON.parse(JSON.stringify(ruleForm.value))
      // 数据权限
      const obj = {
        role: ruleForm.value.role,
        role_owner: {
          data_user_ids: [],
          menu_ids: [],
          field_attr_ids: [],
          warehouse_ids: [],
          goods_category_ids: [],
          button_ids: [],
          data_dept_ids:[]
        }
      }
      dataUser.value.getCheckedNodes().map(res => {
        if (res.data.organization_type === 2) {
          obj.role_owner.data_user_ids.push(res.data.id)
        }
      })
      //菜单权限
      dataMenu.value.getCheckedNodes().map(res => {
        obj.role_owner.menu_ids = obj.role_owner.menu_ids.concat(res.pathValues)
      })
      obj.role_owner.menu_ids = [...new Set(obj.role_owner.menu_ids)]
      //按钮权限
      dataButton.value.getCheckedNodes().map(res => {
        if (+res.data.type === 2) {
          obj.role_owner.button_ids.push(res.data.id)
        }
      })
      //商品权限
      dataGoods.value.getCheckedNodes().map(res => {
        obj.role_owner.goods_category_ids.push(res.id)
      })
      console.log(obj.role_owner.goods_category_ids);
      console.log(dataGoods.value.getHalfCheckedKeys());
      
      // obj.role_owner.goods_category_ids = obj.role_owner.goods_category_ids.concat(dataGoods.value.getHalfCheckedKeys())
      //仓库权限
      dataWarehouse.value.getCheckedNodes().map(res => {
        if (res.id?.indexOf('1-') >= 0) {
          obj.role_owner.warehouse_ids.push(res.warehouse_id)
        }
      })
      //属性权限
      dataField.value.getCheckedNodes().map(res => {
        if (res.field_type === 3) {
          obj.role_owner.field_attr_ids.push(res.id)
        }
      })
      obj.role.status = Number(obj.role.status)
      const selectedIds = dataUser.value.getCheckedNodes().map((item) => item.data.id).filter((id) => typeof id === "string" && id.startsWith("d"));
      const filteredNodes = filterTreeByIds(options.value, selectedIds);
      const depIds = filteredNodes.map((item) =>Number(item.id.replace("d", "")));
      const userIds = simplifyIds(obj.role_owner.data_user_ids);
      obj.role_owner.data_user_ids = userIds
      obj.role_owner.data_dept_ids = depIds
      emits('confirm', obj)
      loading.value.save = true
      loading.value.saveEnable = true
    }
  })
}
const cancel = () => {
  ruleForm.value = {
    role: {
      name: '',
      status:1
    },
    role_owner: {
      menu_ids: [],
      field_attr_ids: [],
      button_ids: [],
      data_user_ids: [],
      goods_category_ids: []
    }
  }
  for(let key in search_list){
    search_list[key] = []
  }
  lastCheckedIds.value = []
  deleteVisible.value = false
  loading.value.saveEnable = false
  loading.value.save = false
  emits('cancel')
}
const confirmEnable = () => {
  ruleForm.value.role.status = true
  confirm()
}
const customFilterMethod = (node, keyword) => {
  return node.label.toLowerCase().includes(keyword.toLowerCase())
}
const search_list = reactive({
  menu_name:[],
  button_name:[],
  goods_category_name:[],
  field_name:[],
  data_user_name:[]
})
const handleMenuRemove = (val) =>{
  ruleForm.value.role_owner.menu_ids = ruleForm.value.role_owner.menu_ids.filter((item) => item !== val);
}
watch(
  () => search_list.menu_name,
  (val) => {
    if (!val.length) return;
    const set = new Set([...ruleForm.value.role_owner.menu_ids, ...val]);
    ruleForm.value.role_owner.menu_ids = Array.from(set);
  }
);
//按钮
const handleButtonRemove = (val) =>{
  ruleForm.value.role_owner.button_ids = ruleForm.value.role_owner.button_ids.filter((item) => item !== val);
}
watch(
  () => search_list.button_name,
  (val) => {
    if (!val.length) return;
    const set = new Set([...ruleForm.value.role_owner.button_ids, ...val]);
    ruleForm.value.role_owner.button_ids = Array.from(set);
  }
);
//商品权限
const handleGoodsRemove = (val) => {
  dataGoods.value.setChecked(val, false, true);
};
watch(
  () => search_list.goods_category_name,
  (val) => {
    if (!val.length) return;
    let goodsData = dataGoods.value.getCheckedKeys()
    const set = new Set([...goodsData, ...val]);
    const setGood = Array.from(set);
    dataGoods.value.setCheckedKeys(setGood)
  }
);
//仓库权限
const handleWarehouseRemove = (val) =>{
  console.log(warehouseData.value);
  dataWarehouse.value.setChecked(val, false, true);
}
watch(
  () => search_list.warehouse_name,
  (val) => {
    if (!val.length) return;
    let warehouseData = dataWarehouse.value.getCheckedKeys()
    const set = new Set([...warehouseData, ...val]);
    const setWarehouse = Array.from(set);
    dataWarehouse.value.setCheckedKeys(setWarehouse)
  }
);
//字段权限
const handleFieldRemove = (val) =>{
  dataField.value.setChecked(val, false, true); 
}
watch(
  () => search_list.field_name,
  (val) => {
    if (!val.length) return;
    let fieldData = dataField.value.getCheckedKeys()
    const set = new Set([...fieldData, ...val]);
    const setField = Array.from(set);
    dataField.value.setCheckedKeys(setField)
  }
);
//数据权限
const handleDataRemove = (val) =>{
  ruleForm.value.role_owner.data_user_ids = ruleForm.value.role_owner.data_user_ids.filter((item) => item !== val);
  handleDataUser(ruleForm.value.role_owner.data_user_ids)
}
watch(
  () => search_list.data_user_name,
  (val) => {
    if (!val.length) return;
    const set = new Set([...ruleForm.value.role_owner.data_user_ids, ...val]);
    ruleForm.value.role_owner.data_user_ids = Array.from(set);
    handleDataUser(ruleForm.value.role_owner.data_user_ids)
  }
);
defineExpose({
  open, data, cancel
})
</script>
<style lang="scss" scoped>
.attribute {
  display: flex;
  height: 400px;
  &>div {
    height: 100%;
      overflow: auto;
    flex: 1;
  border:1px solid #E6E7E9;
    .text {
      text-align: center;
      line-height: 40px;
      background-color:var(--base-table-header-bg-color);
      color: #3487FF;
    }

    // &:not(:last-child) {
    //   border-right: 1px solid #dcdfe6;
    //   margin-right: 5px;
    // }
  }
}

.content {
  align-items: center;
  span {
    margin-left: 5px;
  }
}

.dialogName {
  font-size: 16px;
  font-weight: bold;
}

.input-switch {
  width: calc(100% - 58px);
  margin-right: 10px;
}

:deep(.tab-pane) {
  margin: 0 20px;
  border-radius: 10px;
  .el-tabs__content{
    padding: 8px;
  }

  .el-tabs__header {
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
  }

  .el-tabs__nav {
    width: 100%;
    border-radius: 10px;
    display: flex;
  }

  .el-tabs__item.is-active {
    color: #fff !important;
    background-color: #3487ff !important;
  }

  .el-tabs__item {
    flex: 1;
    color: var(--base-tabs-color) !important;
    text-align: center;
    background: var(--base-color) !important;
    border:1px solid var(--base-border-color) !important;
    &:hover{
    color: #fff !important;
    background-color: #3487ff !important;
    }
  }

  .el-tabs__item:first-child {
    border-top-left-radius: 10px;
  }

  .el-tabs__item:last-child {
    text-align: center;
    border-top-right-radius: 10px;
  }
}

.cascaderPanel {
  overflow: auto;
  height: 400px;

  &:deep(.el-scrollbar__wrap) {
    height: 100% !important;
  }
}

:deep(.el-cascader-menu:last-child) {
  border-right: var(--el-cascader-menu-border);
}
:deep(.el-scrollbar__bar){
  display: block !important;
}
</style>